package com.renren.http.utils;

/**
 * PageUtils.java
 * 
 * 
 * 
 * 
 */
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * @author chenshi
 * @date 2012/09/09
 * 
 */
public class PageUtils {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			URL url = new URL("http://3g.renren.com");
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			InputStream in = null;
			in = url.openStream();
			String content = pipe(in, "utf-8");
			System.out.println(content);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将数据流转字符串
	 * 
	 * @param in
	 *            数据流
	 * @param charset
	 *            编码
	 * 
	 * @return 字符串
	 * 
	 */
	public static String pipe(InputStream in, String charset)
			throws IOException {
		StringBuffer s = new StringBuffer();
		if (charset == null || "".equals(charset)) {
			charset = "utf-8";
		}
		String rLine = null;
		BufferedReader bReader = new BufferedReader(new InputStreamReader(in,
				charset));

		while ((rLine = bReader.readLine()) != null) {
			String tmp_rLine = rLine;
			int str_len = tmp_rLine.length();
			if (str_len > 0) {
				s.append(tmp_rLine);
			}
			tmp_rLine = null;
		}
		in.close();
		return s.toString();
	}

	/**
	 * 将数据流转字符串并写入文件
	 * 
	 * @param in
	 *            数据流
	 * @param charset
	 *            编码
	 * @param file
	 *            写入的文件
	 * @exception IOException
	 * 
	 * @return 字符串
	 * 
	 */
	public static String pipe(InputStream in, String charset, File file)
			throws IOException {
		StringBuffer s = new StringBuffer();
		if (charset == null || "".equals(charset)) {
			charset = "utf-8";
		}
		String rLine = null;
		BufferedReader bReader = new BufferedReader(new InputStreamReader(in,
				charset));
		PrintWriter pw = null;

		FileOutputStream fo = new FileOutputStream(file);
		OutputStreamWriter writer = new OutputStreamWriter(fo, "utf-8");
		pw = new PrintWriter(writer);
		while ((rLine = bReader.readLine()) != null) {
			String tmp_rLine = rLine;
			int str_len = tmp_rLine.length();
			if (str_len > 0) {
				s.append(tmp_rLine);
				pw.println(tmp_rLine);
				pw.flush();
			}
			tmp_rLine = null;
		}
		in.close();
		pw.close();
		return s.toString();
	}

	/**
	 * 获取页面内容
	 * 
	 * @param httpClient
	 *            客户端实例
	 * @param url
	 *            页面URl
	 * 
	 * 
	 */
	public static String getContent(HttpClient httpclient, String url)
			throws Exception {
		
		System.out.println(url);
		String content = null;

		HttpGet httpget = new HttpGet(url);

		HttpResponse response = httpclient.execute(httpget);

		HttpEntity entity = response.getEntity();

		if (entity != null) {
			InputStream instream = entity.getContent();
			try {
				if (entity.getContentEncoding() != null) {
					content = pipe(instream, entity.getContentEncoding()
							.getName());
				} else {
					content = pipe(instream, null);
				}
			} catch (RuntimeException ex) {
				httpget.abort();
				throw ex;
			} finally {
				try {
					instream.close();
				} catch (Exception ignore) {
				}
			}
		}

		return content;
	}

	/**
	 * 获取页面内容
	 * 
	 * @param url
	 *            页面URl
	 * 
	 */
	public static String getContent(String surl) {
		String content = null;
		try {
			URL url = new URL(surl);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			InputStream in = null;
			in = url.openStream();
			content = pipe(in, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return content;
	}

	/**
	 * 展示页面Cookies
	 * 
	 * @param httpclient
	 *            客户端实例
	 * 
	 */
	public static List<Cookie> showCookies(HttpClient httpclient) {
		List<Cookie> cookies = new ArrayList<Cookie>();
		
		System.out.println("============Show Cookies Start==============="
				+ httpclient);
		if (httpclient == null) {
			System.out.println("COOKIES EMPTY 1");
		}
		DefaultHttpClient hc = (DefaultHttpClient) httpclient;
		cookies = hc.getCookieStore().getCookies();
		if (cookies.isEmpty()) {
			System.out.println("COOKIES EMPTY 2");
		} else {
			for (int i = 0; i < cookies.size(); i++) {
				System.out.println("- " + cookies.get(i).toString());
			}
		}
		System.out.println("============Show Cookies End  ==============="
				+ httpclient);
		return cookies;
	}

}